const AV = require( './libs/av-weapp-min.js' );

//初始化leancloud
AV.init( {
    appId: 'YoAMAnOWeOVKP8xbeF1C30s9-gzGzoHsz',
    appKey: 'MsJTHfgUK4SwJlRPxhA4vpQE',
} );

//app.js
App( {
    onLaunch: function( ) {
        this.getUserAuth();
        // this.getUserInfo_test( );
        wx.setStorageSync('logs')
        wx.getLocation( {
            type: 'gcj02',
            success: res => {
                 wx.setStorageSync('location',{
                    latitude:res.latitude,
                    longitude: res.longitude
                })
            }
        } );
    },
    /**
     * 获取用户授权信息
     * @return {[type]} [description]
     */
    getUserAuth: function( ) {
        Promise.resolve( AV.User.current( ) )
            .then( user =>
                user ?
                (
                    user.isAuthenticated( )
                    .then( authed => authed ? user : null )
                ) : null
            ).then( user =>
                user ? user : AV.User.loginWithWeapp( )
            ).then( ( user ) => {
               wx.setStorageSync('user',user );
            } ).
        then(
            ( ) => this.getUserInfo( )
        ).catch( error => console.error( error.message ) );
    },
    /**
     * 获取用户身份信息
     * @return {[type]} [description]
     */
    getUserInfo: function( ) {
        // 调用小程序 API，得到用户信息
        wx.getUserInfo( {
            success: ( { userInfo } ) => {
                let user = AV.User.current( );
                // 更新当前用户的信息
                user.set( userInfo ).save( ).then( user => {
                    // 成功，此时可在控制台中看到更新后的用户信息
                    wx.setStorageSync('user',user );
                } ).catch( console.error );
            }
        } );
    },
    getUserInfo_test: function( ) {
        wx.getUserInfo( {
            success: ( { userInfo } ) => {
                console.log( userInfo )
                this.globalData.userInfo = userInfo;
            }
        } );
    },
    globalData: {
        user:null,
        location:null
    }
} )

